limsResult.derivativeDetialPage = {

    getBtnToolbar: function () {
        let _this = this;
        return {
            type: 'btnToolbar',
            items: [/*{
                type: 'button',
                text: 'GIKAM.BUTTON.SAVE',
                class: 'blue',
                icon: 'save',
                color: 'white',
                onClick: function () {
                    var form = Gikam.getComp('result-derivative-form')
                    if (form.validate()) {
                        _this.save();
                    }
                }
            },*/ {
                type: 'button',
                text: 'GIKAM.BUTTON.BACK',
                icon: 'back',
                onClick: function () {
                    Gikam.getLastModal().close();
                }
            }]
        }
    },

    // 单次添加衍生物grid
    getRunOrderTaskGridParam: function () {
        let _this = this;
        var requestParam = {
            runId_EQ: _this.param.runId,
            status_SB: 'logged',
            flag_EQ: '1',
            derivativeFilter: '1',
        };
        return {
            type: 'grid',
            id: 'result-order-task-grid',
            page: false,
            columns: limsResult.getRunOrderTaskGridColumns(),
            readonly: true,
            url: limsResult.orderTaskUrl + '/queries',
            requestData: requestParam,
            toolbar: [{
                type: 'button',
                text: 'GIKAM.BUTTON.SAVE',
                class: 'blue',
                icon: 'save',
                color: 'white',
                onClick: function () {
                    var form = Gikam.getComp('result-derivative-form')
                    if (form.validate()) {
                        _this.save();
                    }
                }
            }, /*{
                type: 'button',
                text: 'GIKAM.BUTTON.BACK',
                icon: 'back',
                onClick: function () {
                    Gikam.getLastModal().close();
                }
            },*/ {
                type: 'button',
                text: 'T_LIMS_SAMPLE.SAMPLECODE',
                icon: 'select',
                onClick: function () {
                    var mainGrid = Gikam.getComp('result-order-task-grid')
                    var model = Gikam.create('modal', {
                        title: 'T_CORE_CHART.SEARCHRULE',
                        height: '300',
                        width: '400',
                        onAfterClose: function (data) {
                            if (Gikam.isEmpty(data)) {
                                return;
                            }
                            Gikam.postText(limsResult.orderTaskUrl + '/result/queries', Gikam.getJsonWrapper({
                                f: {
                                    sampleCode_IN: data.sampleCode.replace(/[(\r\n)|(\ +)|(，)|(；)|(;)]/g, ','),
                                    runId_EQ: _this.param.runId,
                                    status_SB: 'logged',
                                    flag_EQ: '1',
                                },
                                n: -1
                            }).param({
                                // 衍生物工序条件过滤
                                derivativeFilter: '1',
                            })).done(function (data) {
                                data = JSON.parse(data);
                                mainGrid.loadData(data.rows)
                            })
                        },
                    })
                    Gikam.create('layout', {
                        renderTo: model.window.$dom,
                        center: {
                            items: [{
                                type: 'form',
                                id: 'insert-fileboxnumber-form',
                                fields: [{
                                    field: 'sampleCode',
                                    title: 'T_LIMS_SAMPLE.SAMPLECODE',
                                    type: 'textarea',
                                    colspan: 2,
                                    height: 180,
                                }],
                                onLoadSuccess: function () {
                                },
                                columns: 1,
                                titleWidth: 120
                            }, {
                                type: 'btnToolbar',
                                items: [{
                                    type: 'button',
                                    text: 'GIKAM.BUTTON.CONFIRM',
                                    class: 'blue',
                                    icon: 'save',
                                    color: 'white',
                                    onClick: function () {
                                        var form = Gikam.getComp('insert-fileboxnumber-form')
                                        Gikam.getLastModal().close(form.getData())
                                    }
                                }, {
                                    type: 'button',
                                    text: 'GIKAM.BUTTON.CANCEL',
                                    icon: 'back',
                                    onClick: function () {
                                        Gikam.getLastModal().close()
                                    }
                                }]
                            }]
                        }
                    })
                }
            }, {
                type: 'form',
                id: 'result-derivative-form',
                columns: 3,
                autoSave: false,
                fields: limsResult.getDerivativeFormFields(),
            }],
        }
    },

    // 批量添加衍生物grid
    getRunOrderTaskGridParamMulti: function () {
        let _this = this;
        var requestParam = {
            runId_EQ: _this.param.runId,
            status_SB: 'logged',
            flag_EQ: '1',
            derivativeFilter: '1',
        };
        var columns = limsResult.getRunOrderTaskGridColumns()
        columns.push({
            field: 'generateDerivativeType',
            title: 'T_LIMS_SAMPLE_DERIVATIVE.DERIVATIVETYPE',
            type: 'select',
            category: 'sys',
            validators: ['notEmpty'],
            firstBlank: false,
            param: {
                codeCategoryId: 'derivativeMakeType'
            },
            width: 140,
            editor: true
        }, {
            field: 'mixGroupId',
            title: 'T_LIMS_ORDERTASK.MIXGROUPID',
            validators: ['notEmpty'],
            width: 140,
            editor: true
        }, {
            field: 'derivativeSampleTypeCode',
            title: 'T_LIMS_ORDERTASK.DERIVATIVESAMPLETYPE',
            type: 'select',
            search: true,
            category: 'sampleType',
            firstBlank: false,
            param: {
                filter_derivativeType: 1,
            },
            validators: ['notEmpty'],
            width: 140,
            editor: true
        },)
        return {
            type: 'grid',
            id: 'result-order-task-grid-multi',
            page: false,
            columns: columns,
            // readonly: true,
            url: limsResult.orderTaskUrl + '/queries',
            requestData: requestParam,
            toolbar: [{
                type: 'button',
                text: 'GIKAM.BUTTON.SAVE',
                class: 'blue',
                icon: 'save',
                color: 'white',
                onClick: function () {
                    _this.multiSave()
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.EXPORT',
                icon: 'export',
                onClick: function () {
                    _this.export();
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.IMPORT',
                icon: 'export',
                onClick: function () {
                    _this.upload();
                }
            }, /*{
                type: 'button',
                text: 'GIKAM.BUTTON.BACK',
                icon: 'back',
                onClick: function () {
                    Gikam.getLastModal().close();
                }
            },*/ {
                type: 'button',
                text: 'T_LIMS_SAMPLE.SAMPLECODE',
                icon: 'select',
                onClick: function () {
                    var mainGrid = Gikam.getComp('result-order-task-grid-multi')
                    var model = Gikam.create('modal', {
                        title: 'T_CORE_CHART.SEARCHRULE',
                        height: '300',
                        width: '400',
                        onAfterClose: function (data) {
                            if (Gikam.isEmpty(data)) {
                                return;
                            }
                            Gikam.postText(limsResult.orderTaskUrl + '/result/queries', Gikam.getJsonWrapper({
                                f: {
                                    sampleCode_IN: data.sampleCode.replace(/[(\r\n)|(\ +)|(，)|(；)|(;)]/g, ','),
                                    runId_EQ: _this.param.runId,
                                    status_SB: 'logged',
                                    flag_EQ: '1',
                                },
                                n: -1
                            }).param({
                                // 衍生物工序条件过滤
                                derivativeFilter: '1',
                            })).done(function (data) {
                                data = JSON.parse(data);
                                mainGrid.loadData(data.rows)
                            })
                        },
                    })
                    Gikam.create('layout', {
                        renderTo: model.window.$dom,
                        center: {
                            items: [{
                                type: 'form',
                                id: 'insert-fileboxnumber-form2',
                                fields: [{
                                    field: 'sampleCode',
                                    title: 'T_LIMS_SAMPLE.SAMPLECODE',
                                    type: 'textarea',
                                    colspan: 2,
                                    height: 180,
                                }],
                                onLoadSuccess: function () {
                                },
                                columns: 1,
                                titleWidth: 120
                            }, {
                                type: 'btnToolbar',
                                items: [{
                                    type: 'button',
                                    text: 'GIKAM.BUTTON.CONFIRM',
                                    class: 'blue',
                                    icon: 'save',
                                    color: 'white',
                                    onClick: function () {
                                        var form = Gikam.getComp('insert-fileboxnumber-form2')
                                        Gikam.getLastModal().close(form.getData())
                                    }
                                }, {
                                    type: 'button',
                                    text: 'GIKAM.BUTTON.CANCEL',
                                    icon: 'back',
                                    onClick: function () {
                                        Gikam.getLastModal().close()
                                    }
                                }]
                            }]
                        }
                    })
                }
            },],
        }
    },

    multiSave: function () {
        var _this = this
        var mainGrid = Gikam.getComp('result-order-task-grid-multi')
        var rows = mainGrid.getSelections()
        if (Gikam.isEmpty(rows)) {
            Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM')
            return
        }
        var message = ''
        var m1 = '', m2 = '', m3 = ''
        var mixGroup = new Map()
        rows.forEach(r => {
            if (!r.generateDerivativeType || r.generateDerivativeType === '' || !r.derivativeSampleTypeCode || r.derivativeSampleTypeCode === '') {
                m1 = m1 + r.sampleCode + ','
            } else if (r.generateDerivativeType === 'mix') {
                if (!r.mixGroupId || r.mixGroupId === '') {
                    m1 = m1 + r.sampleCode + ','
                } else {
                    var tasks = mixGroup.get(r.mixGroupId)
                    if (!tasks) {
                        tasks = []
                        tasks.push(r)
                        mixGroup.set(r.mixGroupId, tasks)
                    } else {
                        tasks.push(r)
                        mixGroup.set(r.mixGroupId, tasks)
                    }
                }
            }
        })
        mixGroup.forEach((tasks, mixGroupId) => {
            if (tasks.length <= 1) {
                m2 = m2 + mixGroupId + ','
            } else {
                var sampleType = tasks[0].derivativeSampleTypeCode
                tasks.forEach(t => {
                    var flag = true
                    if (t.derivativeSampleTypeCode !== sampleType && flag) {
                        m3 = m3 + mixGroupId + ','
                        flag = false
                    }
                })
            }
        })
        if (m1 !== '') {
            message = Gikam.propI18N('DERIVATIVES_GENERATE_MESSAGE.M1') + m1 + '<br/>'
        }
        if (m2 !== '') {
            message = message + Gikam.propI18N('DERIVATIVES_GENERATE_MESSAGE.M2') + m2 + '<br/>'
        }
        if (m3 !== '') {
            message = message + Gikam.propI18N('DERIVATIVES_GENERATE_MESSAGE.M3') + m3 + '<br/>'
        }
        if (message !== '') {
            Gikam.confirm('DERIVATIVES_GENERATE_MESSAGE', message, () => {
                workspace.window.showMask()
                var url = limsResult.derivativelUrl + '/derivatives-multi'
                var data = Gikam.getJsonWrapper(null, [null, rows])
                Gikam.postText(url, data).done(req => {
                    Gikam.getLastModal().close()
                }).always(function () {
                    workspace.window.closeMask()
                })
            })
        } else {
            workspace.window.showMask()
            var url = limsResult.derivativelUrl + '/derivatives-multi'
            var data = Gikam.getJsonWrapper(null, [null, rows])
            Gikam.postText(url, data).done(req => {
                Gikam.getLastModal().close()
            }).always(function () {
                workspace.window.closeMask()
            })
        }
    },

    export: function () {
        var activedRow = Gikam.getComp('run-list-grid').getActivedRow();
        Gikam.getText(IFM_CONTEXT + '/core/module/item/files/template-urls' + Gikam.param({
            templateCode: 'LimsDeriSampleGenerateExportTemplate',
            service: 'LimsDeriSampleGenerateExportTemplate',
            id: activedRow.id
        })).done(function (url) {
            Gikam.download(url);
        });
    },

    upload: function () {
        var _this = this;
        var runGrid = Gikam.getComp('run-list-grid');
        var activedRow = runGrid.getActivedRow();
        if (Gikam.isEmpty(activedRow)) {
            return;
        }
        Gikam.create('simpleUploader', {
            id: 'result-info-import',
            dbTable: 'T_LIMS_RUN',
            bizId: activedRow.id,
            autoClose: true,
            multiple: false,
            onAfterClose: function (fields) {
                if (Gikam.isNotEmpty(fields)) {
                    workspace.window.showMask();
                    var url = Gikam.printf(IFM_CONTEXT + '/core/module/item/files/{id}/action/import/' + 'LimsDeriSampleGenerateImportFileFunction', {
                        id: fields[0].id
                    }) + Gikam.param({
                        runId: activedRow.id
                    });
                    Gikam.post(url).done(function (req) {
                        if (req.message){
                            Gikam.alert(req.message)
                        }
                        if (req.url){
                            Gikam.download(req.url);
                        }
                        Gikam.getComp('result-order-task-grid-multi').refresh()
                    }).always(function () {
                        workspace.window.closeMask();
                    });
                }

            }
        });
    },

    getMainTabs: function () {
        let _this = this
        return {
            type: 'tab',
            panels: [{//方式一
                title: 'MODULE.BUSINESS.RESULT.TAB.DERIVATIVE.DERIVATIVE_GENERATE_TYPE_ONE',
                items: [_this.getRunOrderTaskGridParam()]
            }, {
                title: 'MODULE.BUSINESS.RESULT.TAB.DERIVATIVE.DERIVATIVE_GENERATE_TYPE_TWO',
                items: [_this.getRunOrderTaskGridParamMulti()]
            }]
        }
    },

    getBaseFormParam: function () {
        let _this = this
        return {
            type: 'form',
            height: '50%',
            id: 'result-derivative-form',
            columns: 3,
            autoSave: false,
            fields: limsResult.getDerivativeFormFields(),
        }
    },

    save: function () {
        var orderTaskGrid = Gikam.getComp('result-order-task-grid');
        var selections = orderTaskGrid.getSelections();
        if (Gikam.isEmpty(selections)) {
            Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM');
            return;
        }
        let baseForm = Gikam.getComp('result-derivative-form');
        if (Gikam.isFalse(baseForm.validate())) {
            return;
        }
        //多样本混样校验
        let data = baseForm.getData();
        if (data.derivativeType === 'mix' && selections.length < 2) {
            Gikam.alert('MORE.THAN.TWO.SAMPLES.MUST.BE.MIXED');
            return;
        }
        let jsonWrapper = Gikam.getJsonWrapper(data, ['', selections]);
        let url = limsResult.derivativelUrl + '/derivatives';
        Gikam.getLastModal().window.showMask();
        Gikam.postText(url, jsonWrapper).done(function () {
            Gikam.getLastModal().window.closeMask();
            Gikam.getLastModal().close();
            Gikam.getComp('result-run-order-task-with-analyte-grid').refresh();
        }).always(function () {
            Gikam.getLastModal() && Gikam.getLastModal().window.closeMask();
        });
    },

    create: function () {
        let _this = this;
        Gikam.create('layout', {
            renderTo: Gikam.getLastModal().window.$dom,
            /*            center: {
                            items: [/!*this.getBaseFormParam(),*!/ _this.getRunOrderTaskGridParam()]
                        },
                        south: {
                            items: [this.getBtnToolbar()]
                        }*/
            center: {
                items: [_this.getBtnToolbar(), _this.getMainTabs()]
            }
        });
    },

    init: function (param) {
        this.param = param;
        this.create();
    }
};
